package state.bluetooth;

import state.Control;

public class BluetoothClient extends Control {
	private BluetoothConnection conn;
	private boolean isRunning;
	
	public BluetoothClient(BluetoothConnection conn) {
		this.conn = conn;
		start();
	}
	
	public void perform() {
		isRunning = true;
		while (isRunning) {
			if (conn.isClosed()) {
				break;
			}
			long now = System.currentTimeMillis();
			
			// Kiểm tra nếu quá 3s mà có client nào ko gửi data thì đóng connection
			if (now - conn.getLastTimeRecive() > BluetoothUtil.DEFAULT_TIME_OUT_TO_DISCONNECT) {
				conn.close();
				break;
			}

			// Kiểm tra để gửi HEART_BREATH_SIGNAL
			if (now - conn.getLastTimeSend() > BluetoothUtil.HEART_BREATH_SEQUENCE_TIME) {
				conn.sendCommand(BluetoothConnection.HEART_BREATH_SIGNAL); // Gửi HEART_BREATH_SIGNAL
			}
			
			try {
				sleep(BluetoothUtil.HEART_BREATH_SEQUENCE_TIME);
			} catch (InterruptedException e) {
			}
		}
	}
	
	public BluetoothConnection getConnection() {
		return conn;
	}
	
	public boolean isRunning() {
		return isRunning;
	}

	public String getServerDeviceName() {
		return conn.getRemoteDeviceName();
	}
	
	public String getServerName() {
		return conn.getRemoteName();
	}
	
	public void signIn() {
		conn.signIn();
	}
	
	public void signOut() {
		conn.signOut();
	}
	
	public boolean isSignedIn() {
		return conn.isSignIn();
	}
	
	public void detroy() {
		isRunning = false;
		if (conn != null) {
			conn.close();
		}
	}
}
